import React, { Component } from 'react'
import InputWidget from '@/components/basicWidget/InputWidget/index.js'
import Button from '@/components/basicWidget/Button/index.js'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { get, post } from '@/utils/requestUtil.js'
import { withRouterContext } from '@/context/router/routerContext.js'
import { message } from 'antd'
import formValidate from '@/service/validate/formValidate' 
import { Link } from "react-router-dom";
import './index.css'

class Enroll extends Component {

  constructor(props) {
    super(props)
    this.state = {
      username: '',
      password: '',
      repassword: ''
    }
  }

  //校验用户名是否可用
  checkUsername = async (value) => {
    if (!value) return
    let response = await get(`/auth/checkUserNameIsExists/${value}`)
    if (response && response.data) return response.data
    else return false
  }

  //校验是否是邮箱
  validateIsEmail = async (value) => {
    if (!value) return
    const reg = new RegExp('^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$')
    if (!reg.test(value)) return false
    else return true
  }

  //密码长度校验
  validatePassword = async (value) => {
    if (!value) return
    const reg = new RegExp('^[a-z0-9A-Z]{8,16}$')
    if (!reg.test(value)) return false
    else return true
  }

  //校验两次密码是否相同
  validatePasswordIsSame = async (value) => {
    if (!value) return
    if (value === this.state.password) return true
    else return false
  }

  onFormChange = (fieldName) => {
    return async (value) => {
      await new Promise((resolve) => {
        this.setState({
          [fieldName]: value
        }, resolve)
      })
    }
  }

  //注册操作
  doEnroll = async () => {
    let refArray = [this.usernameInput, this.passwordInput, this.repasswordInput]
    const validateResult = await formValidate.validateForm(refArray)
    if (validateResult === false) return false
    const {username, password} = this.state
    const response = await post('/auth/doEnroll', {
      body: JSON.stringify({
        username,
        password
      })
    })
    if (response && response.data && response.data === true) {
      message.success('注册成功')
      this.props.navigate(`/login?username=${username}`)
    } else {
      message.error('注册失败，请联系管理员')
    }
  }

  render() {
    return (
      <div
        className='login-main'
      >
        <div className='login-form-outDiv'>
          <form className='login-form'>
            <h1 style={{ color: 'var(--ordinary-font-color)', textAlign: 'center' }}>注册</h1>
            <InputWidget
              placeholder='请输入用户名'
              style={{ width: '300px', marginBottom: '15px' }}
              prefixName={{content: <UserOutlined />}}
              rules={
                [
                  {
                    validate: formValidate.getValidater('isMust'),
                    failMessage: '用户名不能为空'
                  },
                  {
                    validate: this.validateIsEmail,
                    failMessage: '请输入正确的邮箱格式'
                  },
                  {
                    validate: this.checkUsername,
                    failMessage: '用户名已存在',
                    successMessage: '用户名可用'
                  }
                ]
              }
              ref={ref => {this.usernameInput = ref}}
              onChange={this.onFormChange('username')}
            ></InputWidget>
            <InputWidget
              passwordInput={true}
              style={{ width: '300px', marginBottom: '15px' }}
              placeholder='请输入密码'
              prefixName={{content: <LockOutlined />}}
              rules={
                [
                  {
                    validate: formValidate.getValidater('isMust'),
                    failMessage: '密码不能为空'
                  },
                  {
                    validate: this.validatePassword,
                    failMessage: '密码长度应位8-16位字符或数字',
                    successMessage: '密码可用'
                  }
                ]
              }
              ref={ref => {this.passwordInput = ref}}
              onChange={this.onFormChange('password')}
            ></InputWidget>
            <InputWidget
              passwordInput={true}
              style={{ width: '300px', marginBottom: '15px' }}
              placeholder='请确认密码'
              prefixName={{content: <LockOutlined />}}
              rules={
                [
                  {
                    validate: formValidate.getValidater('isMust'),
                    failMessage: '再次输入密码不能为空'
                  },
                  {
                    validate: this.validatePasswordIsSame,
                    failMessage: '两次密码不相同',
                    successMessage: '两次密码相同'
                  }
                ]
              }
              ref={ref => {this.repasswordInput = ref}}
              onChange={this.onFormChange('repassword')}
            ></InputWidget>
            <Button
              style={{
                width: '300px',
                background: 'var(--button-bg-color)',
                marginBottom: '15px',
                color: 'var(--button-font-color)'
              }}
              type='submit'
              onClick={this.doEnroll}
            >
              注   册
            </Button>
            <div className='login-form-footer'>
              <Link to='/login'>前往登录</Link>
            </div>
          </form>
        </div>

      </div>
    )
  }
}

export default withRouterContext(Enroll)
